package com.smart.community.region.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.community.commons.annotation.ApiLog;
import com.smart.community.commons.enums.ApiLogOperationType;
import com.smart.community.commons.result.Result;
import com.smart.community.region.dto.ShopOwnerDTO;
import com.smart.community.region.service.IShopOwnerService;
import com.smart.community.region.service.IShopOwnerRelationService;
import com.smart.community.region.vo.ShopOwnerVO;
import com.smart.community.region.vo.ShopOwnerRelationVO;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * 店铺业主管理控制器
 * 
 * @author Wu.Liang
 * @version 1.0.0
 * @since 2025-01-30
 */
@Slf4j
@RestController
@RequestMapping("/region/shop-owner")
@Tag(name = "店铺业主管理", description = "店铺业主相关接口")
public class ShopOwnerController {
    
    @Autowired
    private IShopOwnerService shopOwnerService;
    
    @Autowired
    private IShopOwnerRelationService shopOwnerRelationService;
    
    /**
     * 分页查询店铺业主列表
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询店铺业主列表", description = "根据条件分页查询店铺业主列表")
    public Result<IPage<ShopOwnerVO>> getShopOwnerPage(
            @Parameter(description = "当前页", example = "1") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "业主姓名") @RequestParam(required = false) String ownerName,
            @Parameter(description = "业主类型") @RequestParam(required = false) Integer ownerType,
            @Parameter(description = "联系电话") @RequestParam(required = false) String ownerPhone,
            @Parameter(description = "身份证号") @RequestParam(required = false) String ownerIdCard,
            @Parameter(description = "企业名称") @RequestParam(required = false) String companyName,
            @Parameter(description = "邮箱") @RequestParam(required = false) String email,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "关键词搜索") @RequestParam(required = false) String keyword,
            @Parameter(description = "创建开始时间", example = "2025-01-01") @RequestParam(required = false) String createTimeStart,
            @Parameter(description = "创建结束时间", example = "2025-12-31") @RequestParam(required = false) String createTimeEnd) {
        try {
            log.info("分页查询店铺业主列表，当前页：{}，每页大小：{}，业主姓名：{}，业主类型：{}，联系电话：{}，身份证号：{}，企业名称：{}，邮箱：{}，状态：{}，关键词：{}，创建开始时间：{}，创建结束时间：{}", 
                    current, size, ownerName, ownerType, ownerPhone, ownerIdCard, companyName, email, status, keyword, createTimeStart, createTimeEnd);
            
            // 参数校验
            if (current == null || current < 1) {
                return Result.fail("页码必须大于0");
            }
            if (size == null || size < 1 || size > 100) {
                return Result.fail("每页大小必须在1-100之间");
            }
            
            // 调用Service查询
            IPage<ShopOwnerVO> ownerPage = shopOwnerService.getShopOwnerPage(
                new Page<>(current, size), ownerName, ownerType, ownerPhone, ownerIdCard, 
                companyName, email, status, keyword, createTimeStart, createTimeEnd);
            
            log.info("分页查询店铺业主列表成功，总记录数：{}", ownerPage != null ? ownerPage.getTotal() : 0);
            return Result.success("查询成功", ownerPage);
        } catch (Exception e) {
            log.error("分页查询店铺业主列表失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询店铺业主详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询店铺业主详情", description = "根据ID查询店铺业主详情")
    public Result<ShopOwnerVO> getShopOwnerById(
            @Parameter(description = "业主ID", example = "1") @PathVariable Long id) {
        try {
            log.info("查询店铺业主详情，ID：{}", id);
            
            // 参数校验
            if (id == null || id <= 0) {
                return Result.fail("业主ID必须大于0");
            }
            
            // 调用Service查询
            ShopOwnerVO shopOwnerVO = shopOwnerService.getShopOwnerById(id);
            if (shopOwnerVO == null) {
                return Result.fail("业主不存在");
            }
            
            log.info("查询店铺业主详情成功，业主姓名：{}", shopOwnerVO.getOwnerName());
            return Result.success("查询成功", shopOwnerVO);
        } catch (Exception e) {
            log.error("查询店铺业主详情失败，ID：{}", id, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建店铺业主
     */
    @ApiLog(
        logTitle = "创建店铺业主",
        logType = 2,
        moduleName = "店铺业主管理",
        operationType = ApiLogOperationType.ADD
    )
    @PostMapping
    @Operation(summary = "创建店铺业主", description = "创建新的店铺业主")
    public Result<Long> createShopOwner(@RequestBody @Valid ShopOwnerDTO shopOwnerDTO) {
        try {
            log.info("创建店铺业主，业主姓名：{}", shopOwnerDTO.getOwnerName());
            
            // 业务参数校验
            validateShopOwnerDTO(shopOwnerDTO);
            
            // 调用Service创建
            Long ownerId = shopOwnerService.createShopOwner(shopOwnerDTO);
            
            log.info("创建店铺业主成功，业主ID：{}，业主姓名：{}", ownerId, shopOwnerDTO.getOwnerName());
            return Result.success("创建成功", ownerId);
        } catch (Exception e) {
            log.error("创建店铺业主失败，业主姓名：{}", shopOwnerDTO != null ? shopOwnerDTO.getOwnerName() : "未知", e);
            return Result.fail("创建失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新店铺业主
     */
    @ApiLog(
        logTitle = "更新店铺业主",
        logType = 2,
        moduleName = "店铺业主管理",
        operationType = ApiLogOperationType.UPDATE
    )
    @PutMapping("/{id}")
    @Operation(summary = "更新店铺业主", description = "更新店铺业主信息")
    public Result<Boolean> updateShopOwner(
            @Parameter(description = "业主ID", example = "1") @PathVariable Long id,
            @RequestBody @Valid ShopOwnerDTO shopOwnerDTO) {
        try {
            log.info("更新店铺业主，ID：{}，业主姓名：{}", id, shopOwnerDTO.getOwnerName());
            
            // 参数校验
            if (id == null || id <= 0) {
                return Result.fail("业主ID必须大于0");
            }
            // 业务参数校验
            validateShopOwnerDTO(shopOwnerDTO);
            
            // 调用Service更新
            boolean success = shopOwnerService.updateShopOwner(id, shopOwnerDTO);
            if (!success) {
                return Result.fail("业主不存在或更新失败");
            }
            
            log.info("更新店铺业主成功，ID：{}，业主姓名：{}", id, shopOwnerDTO.getOwnerName());
            return Result.success("更新成功", true);
        } catch (Exception e) {
            log.error("更新店铺业主失败，ID：{}，业主姓名：{}", id, shopOwnerDTO != null ? shopOwnerDTO.getOwnerName() : "未知", e);
            return Result.fail("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除店铺业主
     */
    @ApiLog(
        logTitle = "删除店铺业主",
        logType = 2,
        moduleName = "店铺业主管理",
        operationType = ApiLogOperationType.DELETE
    )
    @DeleteMapping("/{id}")
    @Operation(summary = "删除店铺业主", description = "删除店铺业主")
    public Result<Boolean> deleteShopOwner(
            @Parameter(description = "业主ID", example = "1") @PathVariable Long id) {
        try {
            log.info("删除店铺业主，ID：{}", id);
            
            // 参数校验
            if (id == null || id <= 0) {
                return Result.fail("业主ID必须大于0");
            }
            
            // 调用Service删除
            boolean success = shopOwnerService.deleteShopOwner(id);
            if (!success) {
                return Result.fail("业主不存在或删除失败");
            }
            
            log.info("删除店铺业主成功，ID：{}", id);
            return Result.success("删除成功", true);
        } catch (Exception e) {
            log.error("删除店铺业主失败，ID：{}", id, e);
            return Result.fail("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除店铺业主
     */
    @ApiLog(
        logTitle = "批量删除店铺业主",
        logType = 2,
        moduleName = "店铺业主管理",
        operationType = ApiLogOperationType.DELETE
    )
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除店铺业主", description = "批量删除店铺业主")
    public Result<Boolean> batchDeleteShopOwners(@RequestBody List<Long> ids) {
        try {
            log.info("批量删除店铺业主，IDs：{}", ids);
            
            // 参数校验
            if (ids == null || ids.isEmpty()) {
                return Result.fail("业主ID列表不能为空");
            }
            
            // 调用Service批量删除
            boolean success = shopOwnerService.batchDeleteShopOwners(ids);
            if (!success) {
                return Result.fail("批量删除失败");
            }
            
            log.info("批量删除店铺业主成功，删除数量：{}", ids.size());
            return Result.success("批量删除成功", true);
        } catch (Exception e) {
            log.error("批量删除店铺业主失败，IDs：{}", ids, e);
            return Result.fail("批量删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据店铺ID查询业主列表
     */
    @GetMapping("/shop/{shopId}")
    @Operation(summary = "根据店铺ID查询业主列表", description = "根据店铺ID查询关联的业主列表")
    public Result<List<ShopOwnerVO>> getShopOwnersByShopId(
            @Parameter(description = "店铺ID", example = "1") @PathVariable Long shopId) {
        try {
            log.info("根据店铺ID查询业主列表，店铺ID：{}", shopId);
            
            // 参数校验
            if (shopId == null || shopId <= 0) {
                return Result.fail("店铺ID必须大于0");
            }
            
            // 调用Service查询
            List<ShopOwnerVO> ownerList = shopOwnerService.getShopOwnersByShopId(shopId);
            
            log.info("根据店铺ID查询业主列表成功，店铺ID：{}，业主数量：{}", shopId, ownerList.size());
            return Result.success("查询成功", ownerList);
        } catch (Exception e) {
            log.error("根据店铺ID查询业主列表失败，店铺ID：{}", shopId, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据业主ID查询关联店铺列表
     */
    @GetMapping("/{ownerId}/shops")
    @Operation(summary = "根据业主ID查询关联店铺列表", description = "根据业主ID查询关联的店铺列表")
    public Result<List<ShopOwnerRelationVO>> getShopsByOwnerId(
            @Parameter(description = "业主ID", example = "1") @PathVariable Long ownerId) {
        try {
            log.info("根据业主ID查询关联店铺列表，业主ID：{}", ownerId);
            
            // 参数校验
            if (ownerId == null || ownerId <= 0) {
                return Result.fail("业主ID必须大于0");
            }
            
            // 直接调用ShopOwnerRelationService查询
            List<ShopOwnerRelationVO> shopList = shopOwnerRelationService.getShopsByOwnerId(ownerId);
            
            log.info("根据业主ID查询关联店铺列表成功，业主ID：{}，店铺数量：{}", ownerId, shopList.size());
            return Result.success("查询成功", shopList);
        } catch (Exception e) {
            log.error("根据业主ID查询关联店铺列表失败，业主ID：{}", ownerId, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 店铺业主DTO业务规则验证
     */
    private void validateShopOwnerDTO(ShopOwnerDTO shopOwnerDTO) {
        // 业主姓名校验
        if (shopOwnerDTO.getOwnerName() == null || shopOwnerDTO.getOwnerName().trim().isEmpty()) {
            throw new IllegalArgumentException("业主姓名不能为空");
        }
        if (shopOwnerDTO.getOwnerName().length() < 2 || shopOwnerDTO.getOwnerName().length() > 50) {
            throw new IllegalArgumentException("业主姓名长度必须在2-50个字符之间");
        }
        
        // 联系电话校验
        if (shopOwnerDTO.getOwnerPhone() == null || shopOwnerDTO.getOwnerPhone().trim().isEmpty()) {
            throw new IllegalArgumentException("联系电话不能为空");
        }
        if (!shopOwnerDTO.getOwnerPhone().matches("^1[3-9]\\d{9}$")) {
            throw new IllegalArgumentException("联系电话格式不正确");
        }
        
        // 业主类型校验
        if (shopOwnerDTO.getOwnerType() == null) {
            throw new IllegalArgumentException("业主类型不能为空");
        }
        if (shopOwnerDTO.getOwnerType() < 1 || shopOwnerDTO.getOwnerType() > 2) {
            throw new IllegalArgumentException("业主类型必须是1（个人）或2（企业）");
        }
        
        // 企业类型额外校验
        if (shopOwnerDTO.getOwnerType() == 2) {
            if (shopOwnerDTO.getCompanyName() == null || shopOwnerDTO.getCompanyName().trim().isEmpty()) {
                throw new IllegalArgumentException("企业类型业主的企业名称不能为空");
            }
            if (shopOwnerDTO.getCompanyLicense() == null || shopOwnerDTO.getCompanyLicense().trim().isEmpty()) {
                throw new IllegalArgumentException("企业类型业主的营业执照号不能为空");
            }
        }
        
        // 身份证号校验
        if (shopOwnerDTO.getOwnerIdCard() != null && !shopOwnerDTO.getOwnerIdCard().trim().isEmpty()) {
            if (!shopOwnerDTO.getOwnerIdCard().matches("^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$")) {
                throw new IllegalArgumentException("身份证号格式不正确");
            }
        }
        
        // 邮箱校验
        if (shopOwnerDTO.getEmail() != null && !shopOwnerDTO.getEmail().trim().isEmpty()) {
            if (!shopOwnerDTO.getEmail().matches("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$")) {
                throw new IllegalArgumentException("邮箱格式不正确");
            }
        }
        
        // 状态校验
        if (shopOwnerDTO.getStatus() != null && (shopOwnerDTO.getStatus() < 0 || shopOwnerDTO.getStatus() > 1)) {
            throw new IllegalArgumentException("状态必须是0（禁用）或1（启用）");
        }
    }
}
